/**
 * @fileOverview item panel
 * @author huangtonger@aliyun.com
 */

const Util = require('../util/');
const Base = require('../simpleBase');

class Component extends Base {
  getDefaultCfg() {
    return {
      /**
       * 类型
       * @type {string}
       */
      type: 'itempanel',

      /**
       * dom 容器
       * @type {dom}
       */
      container: null,

      /**
       * 获取图项数据
       * @param {function} target - dom object
       * @return {object} model
       */
      getItemModel(target) {
        return Util.clone(target.dataset);
      },

      /**
       * 数据格式化
       * @type {object} - data formatter
       */
      dataFormatters: {
        size: Util.getNodeSize,
        labelOffsetX: Number,
        labelOffsetY: Number
      }
    };
  }

  init() {
    this._initContainer();
  }

  _initContainer() {
    let container = this.container;
    if (container) {
      if (Util.isString(container)) {
        container = document.getElementById(container);
      }
    } else {
      throw new Error('please set the container for the itempanel !');
    }
    this.containerDom = container;
  }
  bindEvent() {
    const editor = this.editor;
    const self = this;
    let dataset;
    Util.delegateEvent(this.containerDom, 'mousedown', '.getItem', function() {
      const getData = self.getItemModel ? self.getItemModel : self.getItemData; // ompatible with getItemData
      dataset = getData(this);
      const page = editor.getCurrentPage();
      page.beginAdd(dataset.type, dataset);
    });
    Util.addEventListener(window, 'mouseup', () => {
      resetStatus();
    });
    Util.addEventListener(window, 'mouseleave', () => {
      resetStatus();
    });
    function resetStatus() {
      const page = editor.getCurrentPage();
      if (dataset) {
        page.cancelAdd();
        dataset = undefined;
      }
    }
  }
}

module.exports = Component;
